import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client/core'
import { CookieService } from './cookie.service';

function getHeaders() {
  const headers: { Authorization?: string; "Content-Type"?: string } = {};
  const token = CookieService.ins().getUserToken();
  if (token) {
    headers["Authorization"] = `Bearer ${token}`;
  }
  headers["Content-Type"] = "application/json";
  return headers;
}

// 与 API 的 HTTP 连接
const httpLink = createHttpLink({
  // 你需要在这里使用绝对路径
  uri: `${import.meta.env.VITE_GRAPHQL_URL}/graphql`,
  fetch: (uri: RequestInfo, options: RequestInit) => {
    options.headers = getHeaders();
    return fetch(uri, options);
  },
})

// 缓存实现
const cache = new InMemoryCache()

// 创建 apollo 客户端
export const apolloClient = new ApolloClient({
  link: httpLink,
  cache,
})